package com.woniu.controller;


import cn.hutool.core.bean.BeanUtil;

import com.woniu.commons.model.Result;
import com.woniu.commons.util.JwtUtil;
import com.woniu.commons.util.RedisUtil;
import com.woniu.model.dto.UserAddressDto;
import com.woniu.model.entity.YUserAddress;
import com.woniu.model.form.AddAddressForm;
import com.woniu.model.form.UpdateAddressForm;
import com.woniu.model.param.AddAddressParam;
import com.woniu.model.param.UpdateAddressParam;
import com.woniu.service.YUserAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 胡歌
 * @since 2024年05月22日
 */
@RestController
@RequestMapping("/yUserAddress")
@Api(tags = "用户操作收货地址的接口")
public class YUserAddressController {

    @Resource
    private YUserAddressService userAddressService;

    @Resource
    private RedisUtil redisUtil;

    @PostMapping("/addAddress")
    @ApiOperation("新增收货地址")
    public Result addAddress(@RequestBody AddAddressForm form, @RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        //获取token
        Integer  userId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("id").toString());
        AddAddressParam param = BeanUtil.toBean(form, AddAddressParam.class);
        param.setUserId(userId);
        userAddressService.addAddress(param);
        return  Result.getResult().setMsg("地址添加成功");
    }
    @PostMapping("/updateAddress")
    @ApiOperation("修改收货地址")
    public  Result updateAddress(UpdateAddressForm form, @RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        //获取token
        Integer  userId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("id").toString());
        UpdateAddressParam Param = BeanUtil.toBean(form, UpdateAddressParam.class);
        Param.setUserId(userId);
        userAddressService.updateAddress( Param);
        return   Result.getResult().setMsg("修改地址成功");
    }

    @GetMapping("/selectAddress")
    @ApiOperation("加载个人所有收货地址")
    public Result<List<UserAddressDto>> selectAddress(@RequestHeader String token){//
        String refreshToken = redisUtil.get(token);
        //获取token
        Integer  userId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("id").toString());
        List<YUserAddress> userAddresses = userAddressService.selectAddress(userId);
        return Result.newListInstance(UserAddressDto.class).setData(BeanUtil.copyToList(userAddresses,UserAddressDto.class));
    }

    @GetMapping("/deleteById/{id}")
    @ApiOperation("删除个人收货地址")
    public Result deleteById(@PathVariable("id") Integer id){
        userAddressService.removeById(id);
        return Result.getResult().setMsg("删除个人收货地址成功");
    }

}

